package com.hz.winnie.demands.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hz.winnie.demands.common.DemandsConstants;
import com.hz.winnie.demands.pojo.User;
import com.hz.winnie.demands.service.UserService;
import com.hz.winnie.demands.utils.CookieUtils;
import com.hz.winnie.demands.utils.MD5Util;

/**
 * @description 登录Controller
 * @author winnie
 * @date 2011-4-3
 * @version 1.0
 */

@Controller
@RequestMapping("/")
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private HttpSession session;

    @RequestMapping("/login")
    public String login(String toUrl, Model model) {
	model.addAttribute("toUrl", toUrl);
	return "login";
    }

    @RequestMapping("/do_login")
    public String doLogin(String toUrl, String userName, String password,
	    boolean remember, HttpServletResponse response,
	    HttpServletRequest request, Model model) throws Exception {
	User user = userService.authUser(userName, MD5Util.md5(password));
	if (user == null) {
	    String errorMsg = "用户名密码错误。";
	    model.addAttribute("message", errorMsg);
	    return "login";
	}
	// 写cookie
	int maxAge = -1;
	if (remember) {
	    maxAge = 60 * 60 * 24;
	}
	CookieUtils.setCookie(request, response,
		DemandsConstants.COOKIE_KEY_DEM_ID, String
			.valueOf(user.getId()), maxAge);

	// 写Session
	session.setAttribute(DemandsConstants.SESSION_KEY_USER, user);
	if (StringUtils.isBlank(toUrl)) {
	    toUrl = "/index.htm";
	}
	return "redirect:" + toUrl;
    }
}
